<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置条件</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" v-if="level == 0 || userInfo.power == 0" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" @click="handleRecord">操作日志</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="writeOffList" @selection-change="handleSelectionChange" ref="tableDateRef">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column label="账号ID" align="left" prop="userId" v-if="columns[0].visible" />
      <el-table-column label="用户名" align="left" prop="userName" v-if="columns[1].visible" width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <div style="cursor:pointer;" @click="handleGoChannel(scope.row, 1)">{{scope.row.userName}}</div>
          <el-button size="mini" type="text" @click="handleGoChannel(scope.row, 2)">查看账号</el-button>
        </template>
      </el-table-column>
      <el-table-column label="所属账户" align="left" prop="parentName" v-if="columns[2].visible" />
      <el-table-column label="今日流水" align="left" prop="todayIncome" v-if="columns[3].visible" />
      <el-table-column label="昨日流水" align="left" prop="yesterdayIncome" v-if="columns[4].visible" />
      <el-table-column label="总流水" align="left" prop="totalIncome" v-if="columns[5].visible" />
      <el-table-column label="余额" align="left" prop="balance" v-if="columns[6].visible" />
      <el-table-column label="费率" align="left" prop="rate" v-if="columns[7].visible">
        <template slot-scope="scope">
          <span>{{scope.row.rate}}%</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="支付宝费率" align="left" prop="zfbrate" v-if="columns[12].visible">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{scope.row.zfbrate}}%</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="账号状态" align="left" prop="status" v-if="columns[8].visible">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="开台权限" align="left" prop="power" v-if="level == 0">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.power" :active-value="0" :inactive-value="1"
            @change="handlePowerChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="createTime" :show-overflow-tooltip="true"
        v-if="columns[9].visible" />
      <el-table-column label="修改时间" align="left" prop="updateTime" :show-overflow-tooltip="true"
        v-if="columns[10].visible" />
      <el-table-column label="备注" align="left" prop="remark" v-if="columns[11].visible" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-coin" @click="handleChangeBalance(scope.row,1)">充值
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-coin" @click="handleChangeBalance(scope.row,2)">扣款
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)">重置密码</el-button>
<!--          <el-button size="mini" type="text" icon="el-icon-view" @click="handleFundRecord(scope.row)">资金记录</el-button>-->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-if="userInfo.userId == 1001"
                     v-hasPermi="['merchant:account:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" style="height:57px;" />


    <!-- 添加或修改核销信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" :width="isMobile?'90%':'500px'" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="核销账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入核销账号" />
        </el-form-item>
        <el-form-item label="核销费率" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入核销费率" />
        </el-form-item>
<!--        <el-form-item label="核销费率(支付宝)" prop="rate">-->
<!--          <el-input v-model="form.zfbrate" placeholder="请输入核销费率(支付宝)" />-->
<!--        </el-form-item>-->
        <el-form-item label="核销备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入核销备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 充值或扣款对话框 -->
    <el-dialog :title="changeBalance.title" :visible.sync="changeBalance.open" :width="isMobile?'90%':'500px'" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="核销账号" prop="userName">
          <el-input v-model="form.userName" :disabled="true" />
        </el-form-item>
        <el-form-item label="金额" prop="balance">
          <el-input v-model="form.balance" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitChangeBalance">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 操作日志对话框 -->
    <el-dialog title="操作日志" :visible.sync="recordOpen" :width="isMobile?'90%':'800px'" append-to-body>
      <el-table v-loading="loading" :data="writeOffRecordList" ref="tableDateRef">
        <el-table-column label="操作对象" align="center" prop="writeOffId" />
        <el-table-column label="操作内容" align="center" prop="description" />
        <el-table-column label="操作时间" align="center" prop="createTime" />
      </el-table>
      <pagination v-show="recordTotal>0" :total="recordTotal" :page.sync="recordQueryParams.pageNum"
        :limit.sync="recordQueryParams.pageSize" @pagination="getRecordList" style="height:57px;" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listWriteOff,
  addWriteOff,
  updateWriteOff,
  changeWriteOffStatus,
  changeWriteOffBalance,
  getWriteOffInfo,
  resetPassword,
  recordList,
  delWriteOff,
  changeWriteOffPower
} from '@/api/merchant/writeOff'
  import { mapGetters } from 'vuex'
  import { delAccount } from '@/api/merchant/account'
import store from '@/store'

  export default {
    name: "writeOffList",
    data() {
      return {
        // 核销列表
        writeOffList: [],
        // 遮罩层
        loading: true,
        // 按钮loading
        buttonLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 总记录条数
        recordTotal: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否现实日志记录弹出层
        recordOpen: false,
        // 表单参数
        form: {
          userId: undefined,
          userName: undefined,
          rate: undefined,
          zfbrate: undefined,
          remark: undefined,
          balance: undefined
        },
        // 改变余额参数
        changeBalance: {
          open: false,
          title: '',
          type: undefined,
        },
        // 操作日志列表
        writeOffRecordList: [],
        // 查询参数
        queryParams: {
          userId: 0,
          pageNum: 1,
          pageSize: 10,
        },
        recordQueryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        // 表单校验
        rules: {
          userName: [{
            required: true,
            message: "核销账号不能为空",
            trigger: "blur"
          }],
          rate: [{
            required: true,
            message: "核销费率不能为空",
            trigger: "blur"
          }],
          balance: [{
            required: true,
            message: "金额不能为空",
            trigger: "blur"
          }],
        },
        // 列信息
        columns: [
          {
            key: 0,
            label: `账号ID`,
            visible: true
          },
          {
            key: 1,
            label: `用户名`,
            visible: true
          },
          {
            key: 11,
            label: `所属账户`,
            visible: true
          },
          {
            key: 2,
            label: `今日流水`,
            visible: true
          },
          {
            key: 3,
            label: `昨日流水`,
            visible: true
          },
          {
            key: 4,
            label: `总流水`,
            visible: true
          },
          {
            key: 5,
            label: `余额`,
            visible: true
          },
          {
            key: 6,
            label: `费率`,
            visible: true
          },
          // {
          //   key: 12,
          //   label: `支付宝费率`,
          //   visible: true
          // },
          {
            key: 7,
            label: `账号状态`,
            visible: true
          },
          // {
          //   key: 12,
          //   label: `开台权限`,
          //   visible: true
          // },
          {
            key: 8,
            label: `创建时间`,
            visible: true
          },
          {
            key: 9,
            label: `修改时间`,
            visible: true
          },
          {
            key: 10,
            label: `备注`,
            visible: true
          },
        ],
        userId: 0,
      }
    },
    computed: {
      ...mapGetters(["level", 'userInfo', 'chooseUserId']),
      ...mapGetters(['isMobile']),
      isPhone() {
        let info = navigator.userAgent;
        //通过正则表达式的test方法判断是否包含“Mobile”字符串
        let isPhone = /mobile/i.test(info);
        //如果包含“Mobile”（是手机设备）则返回true
        return isPhone;
      }
    },
    watch: {
      '$route': function() {
        // console.log(111)
        if (this.$route.query.userId) {
          this.queryParams.userId = this.$route.query.userId;
        }else {
          this.queryParams.userId = ''
        }
        this.getList();
      }
    },
    mounted() {
      // this.queryParams.userId = this.chooseUserId;
      if (this.$route.query.userId) {
        this.queryParams.userId = this.$route.query.userId;
      }
      this.getList();
    },
    methods: {
      // 表单重置
      reset() {
        this.form = {
          userId: undefined,
          userName: undefined,
          rate: undefined,
          remark: undefined,
          balance: undefined
        }
        this.resetForm("form");
      },
      handleGoChannel(row, type) {
        // store.commit('SET_CHOOSE_USERID', row.userId);
        // store.commit('SET_CHOOSE_USER_NAME', row.userName);
        if (type == 1) {
          this.$router.push({
            path: '/writeOff/list',
            query: {
              userId: row.userId
            }
          })
        }else if (type == 2) {
          this.$router.push({
            path: '/account/list',
            query: {
              userId: row.userId
            }
          })
        }
      },
      /** 查询核销信息列表 */
      getList() {
        this.loading = true;
        listWriteOff(this.queryParams).then(response => {
          this.writeOffList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.accountId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加核销";
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            console.log(this.form.userId);
            this.form.parentId = this.chooseUserId;
            if (this.queryParams.userId) {
              this.form.parentId = this.queryParams.userId;
            }
            if (this.form.userId != null) {
              updateWriteOff(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addWriteOff(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.changeBalance.open = false;
        this.reset();
      },
      // 核销状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要' + text + '该核销吗？').then(function () {
          return changeWriteOffStatus(row.userId, row.status);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 核销状态修改
      handlePowerChange(row) {
        let text = row.power === "0" ? "开通" : "禁用";
        this.$modal.confirm('确认要' + text + '吗？').then(function () {
          return changeWriteOffPower(row.userId, row.power);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.status = row.power === "0" ? "1" : "0";
        });
      },
      // 处理充值/扣款按钮
      handleChangeBalance(row, type) {
        this.reset();
        this.changeBalance.open = true;
        this.changeBalance.type = type;
        if (type == 1) {
          this.changeBalance.title = '充值';
        } else {
          this.changeBalance.title = '扣款';
        }
        this.form.userName = row.userName;
        this.form.userId = row.userId;
      },
      //提交充值/扣款按钮
      submitChangeBalance() {
        this.buttonLoading = true;
        changeWriteOffBalance(this.form, this.changeBalance.type).then(response => {
          this.$modal.msgSuccess(this.changeBalance.title + "成功");
          this.cancel();
          this.getList();
        }).finally(() => {
          this.buttonLoading = false;
        })
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const userId = row.userId || this.ids
        getWriteOffInfo(userId).then(response => {
          this.loading = false;
          this.form = response.data;
          this.open = true;
          this.title = "修改核销信息";
        });
      },
      /**重置密码按钮操作 */
      handleResetPwd(row) {
        this.$modal.confirm('是否确认重置"' + row.userName + '"的密码？').then(function () {
          return resetPassword(row.userId);
        }).then(() => {
          this.$modal.msgSuccess("重置成功，重置后密码为：123456");
        }).catch(() => {});
      },
      handleFundRecord(row) {
        this.$router.push({
          path: '/capitalRecord/list',
          query: {
            userId: row.userId
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const accountIds = row.userId;
        this.$modal.confirm('是否确认删除账号信息编号为"' + accountIds + '"的数据项？').then(() => {
          this.loading = true;
          return delWriteOff(accountIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 获取操作日志列表 */
      getRecordList() {
        this.recordQueryParams.userId = this.chooseUserId;
        recordList(this.recordQueryParams).then(response => {
          this.writeOffRecordList = response.rows;
          this.recordTotal = response.total;
          this.loading = false;
        });
      },
      /** 操作日志按钮操作 */
      handleRecord() {
        this.recordOpen = true;
        this.loading = true;
        this.getRecordList();
      },
    }
  }

</script>
